package featureExtraction;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;


public class TokenDetection {

	
	// Pixel Type to be used in the run length enconding
	private enum PixelType
	{
		BLACK,
		WHITE
	}
	
	public TokenDetection()
	{
	}
	
	public TokenCollection SegmentImageTokens(BufferedImage image)
	{
		TokenCollection tokenCollection = new TokenCollection(image);
		byte[][] workingImage = new byte[image.getWidth()][image.getHeight()];
		for (int i = 2; i < image.getWidth() - 2; i++)
		{
			for (int j = 2; j < image.getHeight() - 2; j++)
			{
				if (image.getRGB(i, j) != 0xFFFFFFFF && workingImage[i][j] == 0)
				{
					TokenRaw token = new TokenRaw();
					token.CreateToken(image, workingImage, i, j);
//					token.CreateOriginal(image);
					tokenCollection.AddCharToken(token);
//					token.SegmentArray = null;
//					if ((token.X1 - token.X0) * (token.Y1 - token.Y0) > 4)
//						tokenCollection.AddCharToken(token);
//					else
//						token.DeleteTokenFromImage(image);
				}
			}
		}
		tokenCollection.CleanTokenCollection();

		workingImage = null;
		return tokenCollection;
	}
	
	
	// for debugging purposes only
	public BufferedImage highlightTokens(TokenCollection tc, BufferedImage image)
	{
//		String userFolder = System.getProperty("user.dir");
//		for (int i = 0; i < tc.Tokens.size(); i++)
//		{
//			TokenRaw ct = tc.Tokens.get(i);
//			File outputFile = new File(userFolder + "\\temp2\\" + new Random().nextLong() + ".png");
//			try {
//				ImageIO.write(ImageArrayUtil.CreateResizedCopy(ImageArrayUtil.CreateSubImage(image, ct.X0, ct.X1, ct.Y0, ct.Y1), 11, 23), "png", outputFile);
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
		
		Graphics2D g = (Graphics2D) image.getGraphics();
		for (int i = 0; i < tc.Tokens.size(); i++)
		{
			TokenRaw ct = tc.Tokens.get(i);
			g.setColor(new Color(0xFFFF0000));
			g.drawRect(ct.X0, ct.Y0, ct.X1 - ct.X0, ct.Y1 - ct.Y0);
		}
		return image;
	}
	
}
